<?php
Class C_relation extends Cemvc_Control_Base
{
  public $rel_types = array(FATHER=>"爸爸",
			    MOTHER=>"妈妈",
			    WIFE=>"妻子",
			    HUSBAND=>"丈夫",
			    SON=>"儿子",
			    DAUGHTER=>"女儿");
  

  private $db;

  public function __construct()
  {
    parent::__construct();
    $this->db = new M_qin_users();
    /* $this->db->SetDbCodeNames("utf8"); */

    if(isset($_REQUEST['userid']) && $_REQUEST['userid'])
      {
	$user = $this->db->get($_REQUEST['userid']);
	$region = new M_qin_region();
	$user['region'] = $user['region_code'] ? $region->get_full_name($user['region_code']) : "";
	$user['gender_str'] = $user['gender'] == MALE ? '男' : '女';
	$user["figureurl"] = M_Tools::get_figure_url($user["figureurl"], $user["gender"]);
	$this->view->assign("user", $user);
	$this->user = $user;

	if (isset($_SESSION["id"]) && 
	    ($_SESSION["id"] == $user["creator"] ||	/* I create the user */
	     $_SESSION["id"] == $user["id"] ||	/* I am the user */
	     ($_SESSION["creator"] > 0 && $_SESSION["creator"] == $user["creator"]))) /* we were created with a same user */
	  {
	    $this->view->assign("authorized", 1);
	  }
      }
    $this->view->assign("open", M_Options::get_open_state());
    $this->view->assign("relation_names", array("fathers"=>"父亲",
						"mothers"=>"母亲",
						"mates"=>"配偶",
						"sons"=>"子女"));
  }

  public function add()
  {
    /* include_once "QinRegion.class.php"; */
    /* include_once "QinUtility.class.php"; */
    if (!isset($_REQUEST["userid"]) && !isset($_SESSION["id"]))
      {
    	$this->redirect("users/login");
    	return;
      }
    $id = isset($_REQUEST['userid']) ? $_REQUEST['userid'] : $_SESSION["id"];
    $user = $this->db->get($id); 
    $user["figureurl"] = M_Tools::get_figure_url($user["figureurl"], $user["gender"]);

    /* use the same location of the creator by default */
    $prov_id = substr($user["region_code"], 0, 2)."0000";
    $city_id = substr($user["region_code"], 0, 4)."00";
    $region = new M_qin_region();
    $provinces = $region->getProvinceList();
    $cities = $region->getCitiesList($prov_id);
    $towns = $region->getTownsList($city_id);

    $this->view->assign("provinces", M_Tools::make_options($provinces, $prov_id));
    $this->view->assign("cities", M_Tools::make_options($cities, $city_id));
    $this->view->assign("towns", M_Tools::make_options($towns, $user["region_code"]));

    $this->view->assign("rel_type", M_Tools::make_options($this->rel_types));
    $this->view->assign("creator", $_SESSION["id"]);
    $this->view->assign("user", $user);
    $this->view->assign("male", MALE);
    $this->view->assign("female", FEMALE);
    $this->display();
  }
  public function request()
  {
    if (!isset($_REQUEST['relid']) || empty($_REQUEST['relid']))
      die("You must specify a user to bind.");
    if (!isset($_REQUEST['userid']) || empty($_REQUEST['userid']))
      {
	$this->redirect("users/login");
	/* die("You must specify a role id to bind."); */
      }

    $rel = $this->db->get($_REQUEST['relid']);
    $user = $this->db->get($_REQUEST['userid']);
    /* var_dump($user); */
    $this->view->assign("rel", $rel);
    $this->view->assign("user", $user);
    $this->view->assign("rel_type", M_Tools::make_options($this->rel_types));
    $this->display();
  }
  public function submit_request()
  {
    /* print_r($_POST); */
    $request = new M_qin_request();
    $request->insert_request($_POST);
    $this->view->assign("user", $this->db->get($_POST["user_id"])); 
    $this->display();
  }
  public function submit()
  {
    if (!isset($_POST['rel_type']) || empty($_POST['rel_type']))
      die("You must specify a relation type.");

    $user_created = $this->db->add($_POST);

    /* ****************************************************************** */
    /* get the last user id I added */
    if (!$user_created || !$user_created['id'])
      {
	//die("I can't find the least insert user, may be insert person failed. <br/>Please contact with the Administrator for help.");
	$this->view->assign("error", "I can't find the least insert user, may be insert person failed. <br/>Please contact with the Administrator for help.");
	$this->display();
	return;
      }

    /* var_dump($_REQUEST); */
    /* ***************************************************************** */
    /* transform and create the relation */
    $relation = new M_qin_relation();
    $res = $relation->correct_relation($_POST["roleid"], $user_created["id"], $_POST["rel_type"]);
    $relation->add($res["user_id"], $res["rel_id"], $res["rel_type"]);

    $this->redirect("relation/add_possible_relation?userid=".$_POST["roleid"]."&user_id=".$res["user_id"]
		    ."&rel_id=".$res["rel_id"]
		    ."&rel_type=".$res["rel_type"]
		    ."&created=".$user_created["id"]);
  }

  public function add_possible_relation()
  {
    if (!isset($_REQUEST["user_id"]) || empty($_REQUEST["user_id"]) ||
	!isset($_REQUEST["rel_id"]) || empty($_REQUEST["rel_id"]) ||
	!isset($_REQUEST["rel_type"]) || empty($_REQUEST["rel_type"]) ||
	!isset($_REQUEST["created"]) || empty($_REQUEST["created"]) )
      {
	die("do must specify user_id/rel_id/rel_type and created.");
      }

    /* ****************************************************************** */
    /* get user info */
    $user_created = $this->db->get($_REQUEST["created"]);
    $this->view->assign("user_created", $user_created);

    $userid = $_REQUEST["created"] == $_REQUEST["user_id"] ? $_REQUEST["rel_id"] : $_REQUEST["user_id"];
    $role = $this->db->get($userid);
    $this->view->assign("user", $role);
    $this->view->assign("users", array($user_created["id"]=>$user_created["realname"],
				       $userid => $role["realname"]));

    /* prompt possible relation with exists person */
    $rels = array();
    
    $db = new M_qin_relation();
    if ($_REQUEST["rel_type"] == FATHER)
      {
	if ($_REQUEST["created"] == $_REQUEST["user_id"])
	  {
	    /* the father's mates may be the mother of the son. */
	    /* the reason for "may be " is that, a father may have more than one wives */
	    $mates = $db->get_mates($_REQUEST["rel_id"], RESOURCE_STATE_INIT);
	    if (is_array($mates) && count($mates) > 0)
	      $rels[$_REQUEST["user_id"]] = array("rels" => $mates, 
						  "rel_type"=>MOTHER, 
						  "rel_type_name"=>$this->rel_types[MOTHER]);
	  }
	else if ($_REQUEST["created"] == $_REQUEST["rel_id"])
	  {
	    /* the son's mother may be the mate of the father */
	    $mother = $db->get_mothers($_REQUEST["user_id"], RESOURCE_STATE_INIT);
	    if ($mother)
	      $rels[$_REQUEST["rel_id"]] = array("rels" => array($mother),
						 "rel_type" => WIFE, 
						 "rel_type_name" => $this->rel_types[WIFE]);
	  }
      }
    else if ($_REQUEST["rel_type"] == MOTHER)
      {
	if ($_REQUEST["created"] == $_REQUEST["user_id"])
	  {
	    /* the mother's mates may be the father of the son. */
	    $mates = $db->get_mates($_REQUEST["rel_id"], RESOURCE_STATE_INIT);
	    if (is_array($mates) && count($mates) > 0)
	      $rels[$_REQUEST["user_id"]] = array("rels" => $mates, 
						  "rel_type"=>FATHER,
						  "rel_type_name"=>$this->rel_types[FATHER]);
	  }
	else if ($_REQUEST["created"] == $_REQUEST["rel_id"])
	  {

	    /* the son's father may be the mate of the mother */
	    $father = $db->get_fathers($_REQUEST["user_id"], RESOURCE_STATE_INIT);
	    if ($father)
	      $rels[$_REQUEST["rel_id"]] = array("rels" => array($father),
						 "rel_type" => HUSBAND, 
						 "rel_type_name" => $this->rel_types[HUSBAND]);
	  }
      }
    else if ($_REQUEST["rel_type"] == WIFE)
      {
	if ($_REQUEST["created"] == $_REQUEST["user_id"])
	  {
	    /* the wife's son may be also the son of his husband. */
	    $sons = $db->get_sons($_REQUEST["rel_id"], RESOURCE_STATE_INIT);
	    if (is_array($sons) && count($sons) > 0)
	      $rels[$_REQUEST["user_id"]] = array("rels" => $sons, 
						  "rel_type"=>SON,
						  "rel_type_name"=>$this->rel_types[SON]);
	  }
	else if ($_REQUEST["created"] == $_REQUEST["rel_id"])
	  {

	    /* the husband's son may be also the son of his wife. */
	    $sons = $db->get_sons($_REQUEST["user_id"], RESOURCE_STATE_INIT);
	    if (is_array($sons) && count($sons) > 0)
	      $rels[$_REQUEST["rel_id"]] = array("rels" => $sons, 
						 "rel_type"=>SON,
						 "rel_type_name"=>$this->rel_types[SON]);	
	  }
      }

    if($rels)
      $this->view->assign("relations", $rels);

    $this->view->assign("rel_types", $this->rel_types);
    $this->display();
  }

  public function insert($user_id=null, $rel_id=null, $rel_type=null)
  {
    $user_id = isset($_REQUEST["userid"]) ? $_REQUEST["userid"] : $user_id;
    $rel_id = isset($_REQUEST["rel_id"]) ? $_REQUEST["rel_id"] : $rel_id;
    $rel_type = isset($_REQUEST["rel_type"]) ? $_REQUEST["rel_type"] : $rel_type;

    $relation = new M_qin_relation();
    $res = $relation->correct_relation($user_id, $rel_id, $rel_type);
    $relation->add($res["user_id"], $res["rel_id"], $res["rel_type"]);

    $this->display();
  }

  public function show()
  {
    if (!isset($_REQUEST['userid']) || empty($_REQUEST['userid']))
      die("You must specify a user id to show.");

    $user_id = $_REQUEST["userid"];
    $relations = array();

    /* get family data */
    $db = new M_qin_relation();
    $relations["mothers"] = $db->get_mothers($user_id);
    $relations["fathers"] = $db->get_fathers($user_id);
    $relations["mates"] = $db->get_mates($user_id);
    $relations["sons"] = $db->get_sons($user_id);
    /* var_dump($relations); */
    $this->view->assign("relations", $relations);
    $this->display();
  }
  public function history()
  {
    if (!isset($_REQUEST['relationid']) || empty($_REQUEST['relationid']))
      die("You must specify a relationid id to show.");
    if (!isset($_REQUEST['userid']) || empty($_REQUEST['userid']))
      die("You must specify a user id to show.");

    $user_id = $_REQUEST['userid'];
    $user = $this->db->get($user_id);
    $reverse_relation  = array( FATHER =>$user['gender']==MALE ? "儿子" : "女儿",
				MOTHER =>$user['gender']==MALE ? "女儿" : "儿子", 
				WIFE  =>"丈夫");
    $relation = array(FATHER => "父亲", 
		      MOTHER => "母亲", 
		      WIFE => "妻子");

    $history = new M_qin_history();
    $res = $history->get_history_with_content(CONTENT_TYPE_RELATION, $_REQUEST["relationid"]);

    $relation_history = array();
    foreach($res as $item)
      {
	$item["content"] = unserialize(base64_decode($item["content"]));
	$item["member"] = $item["content"]["user_id"] == $user_id ? 
	  $item["content"]["rel_name"] : $item["content"]["user_name"];
	$item["relation"] = $item["content"]["user_id"] == $user_id ? $relation[$item["content"]["rel_type"]] : 
	  $reverse_relation[$item["content"]['rel_type']];
	$relation_history[] = $item;
      }

    $this->view->assign("history", $relation_history);
    $this->display();
  }
  public function restore()
  {
    if (!isset($_REQUEST["relationid"]) || empty($_REQUEST["relationid"]))
      die("You must specified a relation id to edit.");
    if (!isset($_REQUEST["historyid"]) || empty($_REQUEST["historyid"]))
      die("You must specified an history id to restore.");
   
    $relation = new M_qin_relation();
    $e = $relation->restore($_REQUEST["relationid"], $_REQUEST["historyid"]);
    $rel_id = $_REQUEST["userid"] == $e["user_id"] ? $e["rel_id"] : $e["user_id"];
    $this->redirect("relation/relation_restore_complete?userid=".$_REQUEST["userid"]."&relid=".$rel_id."&historyid=".$_REQUEST["historyid"]);
  }
  public function relation_restore_complete()
  {
    if (!isset($_REQUEST["historyid"]) || empty($_REQUEST["historyid"]))
      die("You must specified an history id to restore.");

    /* get all the direct relation members, such as mothers/fathers/sons/mates; to clear the cache with these person */
    $relation = new M_qin_relation();
    $res = $relation->get_related_members($_REQUEST['userid']);
    $this->view->assign("related_members", $res);
    $this->view->assign("historyid", $_REQUEST["historyid"]);
    $this->view->assign("relid", $_REQUEST["relid"]);
    $this->display();
  }
  public function delete()
  {
    if (!isset($_REQUEST['relationid']) || empty($_REQUEST['relationid']))
      die("You must specify a user id to show.");

    $relation = new M_qin_relation();
    $res = $relation->delete($_REQUEST['relationid']);
    $this->redirect("relation/delete_complete?relationid=".$_REQUEST['relationid']."&userid=".$_REQUEST['userid']);
  }
  public function delete_complete()
  {
    $relation = new M_qin_relation();
    $res = $relation->get_related_members($_REQUEST['userid']);
    $this->view->assign("related_members", $res);

    $this->view->assign("relationid", $_REQUEST['relationid']);
    $this->view->assign("userid", $_REQUEST['userid']);
    $this->display();
  }
  public function ajax_insert()
  {
    $relation = new M_qin_relation();
    $res = $relation->correct_relation($_REQUEST["user_id"], $_REQUEST['rel_id'], $_REQUEST["rel_type"]);
    $relation->add($res["user_id"], $res["rel_id"], $res["rel_type"]);

    die(json_encode(array("resp_id"=>RESP_OK, "resp_str"=>"insert relation successful.")));
  }
}